import { onMounted, onUnmounted } from "vue"
const _cachePrefix = 'qx@'

export const useStoreageListener = (key, callBack) => {
    let keys = Array.isArray(key) ? key : [key]
    keys = keys.map(key => _cachePrefix + key)
    const listener = ({ key, newValue }) => {
        keys.includes(_cachePrefix + key) && newValue && callBack()
    }
    onMounted(() => {
        window.addEventListener('storage', listener)
    })
    onUnmounted(() => {
        window.removeEventListener('storage', listener)
    })
}

export const scopeStorage = (scope) => new Proxy({}, {
    get(_, k) {
        let v = localStorage.getItem(k)
        try {
            v = JSON.parse(v)
        } catch (e) {

        }

        return v
    },
    set(_, k, v) {
        // scopeStorageKeys.add(k)
        localStorage.setItem('__', localStorage.getItem('__') + k + ',')
        if (typeof v === 'object') {
            v = JSON.stringify(v)
        }
        localStorage.setItem(k, v)
        return true
    }
})
export const storage = scopeStorage()

export const clearnScopeStorageKeys = () => {
    console.log('scopeStorageKeys----', scopeStorageKeys)
    // Array.from(scopeStorageKeys).forEach(k => localStorage.removeItem(k))
    // storage['__'].split(',').forEach((k) => {
    //     localStorage.removeItem(k)
    // })
}

const scopeStorageKeys = new Set(storage.__)

console.error('这是缓存key', scopeStorageKeys)
// storage.clear()